﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using RiskMan.Config;
using RiskMan.DataClass.Models;
using RiskMan.DataClass.Stops;
using RiskMan.Views.Dialogs;

namespace RiskMan.Views.Stop
{
    /// <summary>
    /// Interaction logic for test.xaml
    /// </summary>
    public partial class Test
    {
        List<Trade> trades;
        private StopsModel Slm;

        public Test(StopsModel slm)
        {
            InitializeComponent();
            Slm = slm;


            #region ClientCode
            trades = MainWindow.StaticLevel._dataProvider.GetTradeList();
            CmbxClientCode.ItemsSource = trades.Select(a => a.ClientCode).ToList();
            CmbxClientCode.SelectedIndex = 0;
            for (int i = 0; i < CmbxClientCode.Items.Count; i++)
            {
                if (CmbxClientCode.Items[i].ToString() == slm.ClientCode)
                    CmbxClientCode.SelectedIndex = i;
            }
            #endregion

            #region Seccode
            CmbxInstrument.ItemsSource = MainWindow.StaticLevel._dataProvider.GetSeccodeList();
            CmbxInstrument.SelectedIndex = 0;
            for (int i = 0; i < CmbxInstrument.Items.Count; i++)
            {
                if (CmbxInstrument.Items[i].ToString() == slm.Instrument)
                    CmbxInstrument.SelectedIndex = i;
            }
            #endregion

            #region Типы стопов
            List<String> TypeStopList = new List<String>() 
            {
                Cfg.StopLimit,
                Cfg.TakeProfit,
                Cfg.StopTakeOrder,
                Cfg.LinkedOrder,
                Cfg.TakeProfitLimitOrder
            };
            CmbxTypeStop.ItemsSource = TypeStopList;
            CmbxTypeStop.SelectedIndex = 0;
            if (String.IsNullOrEmpty( Slm.TypeStop))
                CmbxTypeStop.SelectedValue = Slm.TypeStop;

            #endregion

            #region TypePriceList
            List<String> TypePriceList = new List<String>() 
            {
                Cfg.ValutPrice,
                Cfg.Persent
            };
            CmbxSlOtstup.ItemsSource = TypePriceList;
            CmbxSlOtstup.SelectedIndex = 0;
            if (String.IsNullOrEmpty(Slm.StopLimitOtstupType))
                CmbxSlOtstup.SelectedValue = Slm.StopLimitOtstupType;

            CmbxSlSpred.ItemsSource = TypePriceList;
            CmbxSlSpred.SelectedIndex = 0;
            if (String.IsNullOrEmpty(Slm.StopLimitSpredType))
                CmbxSlSpred.SelectedValue = Slm.StopLimitSpredType;

            CmbxlSlBreakeven.ItemsSource = TypePriceList;
            CmbxlSlBreakeven.SelectedIndex = 0;
            if (String.IsNullOrEmpty(Slm.StopLimitBreakevenType))
                CmbxlSlBreakeven.SelectedValue = Slm.StopLimitBreakevenType;

            CmbxTpPriceActivation.ItemsSource = TypePriceList;
            CmbxTpPriceActivation.SelectedIndex = 0;
            if (String.IsNullOrEmpty(Slm.TakeProfitPriceActivationType))
                CmbxTpPriceActivation.SelectedValue = Slm.TakeProfitPriceActivationType;

            CmbxTpOtstupMinMax.ItemsSource = TypePriceList;
            CmbxTpOtstupMinMax.SelectedIndex = 0;
            if (String.IsNullOrEmpty(Slm.TakeProfitOtstupMinMaxType))
                CmbxTpOtstupMinMax.SelectedValue = Slm.TakeProfitOtstupMinMaxType;

            CmbxTpSpred.ItemsSource = TypePriceList;
            CmbxTpSpred.SelectedIndex = 0;
            if (String.IsNullOrEmpty(Slm.TakeProfitSpredType))
                CmbxTpSpred.SelectedValue = Slm.TakeProfitSpredType;
            
            CmbxLimitPrice.ItemsSource = TypePriceList;
            CmbxLimitPrice.SelectedIndex = 0;
            if (String.IsNullOrEmpty(Slm.LimitPriceType))
                CmbxLimitPrice.SelectedValue = Slm.LimitPriceType;
            #endregion

            #region другие комбобоксы
            List<String> TypePriceForStopsList = new List<String>() 
            {
                Cfg.StopFromLastPriceDeal, 
                Cfg.StopFromAvaregePriceDeal,
            };
            CmbxTypePriceForStop.ItemsSource = TypePriceForStopsList;
            CmbxTypePriceForStop.SelectedIndex = 0;
            if (String.IsNullOrEmpty(Slm.TypePriceForStop))
                CmbxTypePriceForStop.SelectedValue = Slm.TypePriceForStop;

            List<String> TypeCalculationList = new List<String>() 
            {
                Cfg.StopTypeCalculationBySetting, 
                Cfg.StopTypeCalculationFromDeposit
            };
            CmbxTypeCalculation.ItemsSource = TypeCalculationList;
            CmbxTypeCalculation.SelectedIndex = 0;
            if (String.IsNullOrEmpty(Slm.TypeCalculation))
                CmbxTypeCalculation.SelectedValue = Slm.TypeCalculation;

            List<String> TypeKillAndRemoveLimitFromStopLimitList = new List<String>()
            {
                Cfg.Unknown,
                Cfg.StopKillAndRemoveFromTime,
                Cfg.StopKillAndRemoveFromSpred,
                Cfg.StopKillAndRemoveFromTimeAndSpred
            };
            CmbxKillOrderType.ItemsSource = TypeKillAndRemoveLimitFromStopLimitList;
            CmbxKillOrderType.SelectedIndex = 0;
            if (String.IsNullOrEmpty(Slm.KillOrderType))
                CmbxKillOrderType.SelectedValue = Slm.KillOrderType;
            #endregion

            if (Slm.TypeSingleOrMultiStopl)
                RbtnMultiStop.IsChecked = true;
            else
                RbtnSinglStop.IsChecked = true;

            #region Стоп-лимит

            TxbxSlOtstup.Text = Slm.StopLimitOtstup.ToString();
            TxbxSlFromEnterMoney.Text = Slm.StopLimitFromEnterMoney.ToString();
            TxbxSlSpred.Text = Slm.StopLimitSpred.ToString();
            ChbxSlMarkerOrder.IsChecked = Slm.StopLimitIsMarketOrder;
            TxbxSlBreakeven.Text = Slm.StopLimitBreakeven.ToString();
            TxbxSlBreakevenOtstup.Text = Slm.StopLimitBreakOtstup.ToString();

            #endregion

            #region MyRegion

            TxbxTpPriceActivation.Text = Slm.TakeProfitPriceActivation.ToString();
            TxbxTpFromEnterMoney.Text = Slm.TakeProfitFromEnterMoney.ToString();
            TxbxTpOtstupMinMax.Text = Slm.TakeProfitOtstupMinMax.ToString();
            TxbxTpSpred.Text = Slm.TakeProfitSpred.ToString();
            ChbxTpMarkerOrder.IsChecked = Slm.TakeProfitIsMarketOrder;

            #endregion

            #region Снятие заявки

            TxbxTimeWiatOpenPoz.Text = Slm.TimeWaitForKillOrderFromStop.ToString();
            TxbxSpredForKillOrderOpen.Text = Slm.SpredWaitForKillOrderFromStop.ToString();
            
            #endregion

            #region Лимитная заявка

            TxbxLimitPrice.Text = Slm.LimitPrice.ToString();
            TxbxLimitFromEnterMoney.Text = Slm.LimitFromEnterMoney.ToString();

            #endregion

            DataContext = Slm;

        }

        private void BtnSave_Click(object sender, RoutedEventArgs e)
        {
            bool error=false;
            try
            {
                if (CmbxClientCode.SelectedIndex > 0)
                {
                    Slm.ClientCode = CmbxClientCode.SelectedValue.ToString();
                    List<Trade> trades = MainWindow.StaticLevel._dataProvider.GetTradeList();
                    TxblxClientCode.Foreground = Brushes.White;

                    for (int i = 0; i < trades.Count; i++)
                        if (trades[i].ClientCode == Slm.ClientCode)
                            Slm.Account = trades[i].Account;
                }
                else
                {
                    TxblxClientCode.Foreground = Brushes.Red;
                    error = true;
                }

                if (CmbxInstrument.SelectedIndex > 0)
                {
                    Slm.Instrument = CmbxInstrument.SelectedValue.ToString();
                    TxblInstrument.Foreground = Brushes.White;
                }
                else
                {
                    TxblInstrument.Foreground = Brushes.Red;
                    error = true;

                }

                Slm.TypeCalculation = CmbxTypeCalculation.SelectedItem.ToString();
                Slm.TypeStop = CmbxTypeStop.SelectedItem.ToString();
                Slm.TypePriceForStop = CmbxTypePriceForStop.SelectedItem.ToString();

                #region Стоп-лимит

                if (Slm.TypeStop == Cfg.StopLimit || Slm.TypeStop == Cfg.StopTakeOrder ||
                    Slm.TypeStop == Cfg.LinkedOrder)
                {
                    if (!String.IsNullOrEmpty(TxbxSlOtstup.Text) && Convert.ToDouble(TxbxSlOtstup.Text)>0)
                    {
                        Slm.StopLimitOtstup = Convert.ToDouble(TxbxSlOtstup.Text);
                        TxblSlOtstup.Foreground = Brushes.White;
                    }
                    else
                    {
                        TxblSlOtstup.Foreground = Brushes.Red;
                        error = true;
                    }
                    if (!String.IsNullOrEmpty(TxbxSlFromEnterMoney.Text))
                    {
                        Slm.StopLimitFromEnterMoney = Convert.ToDouble(TxbxSlFromEnterMoney.Text);
                        TxblSlFromEnterMoney.Foreground = Brushes.White;
                    }
                    else
                    {
                        TxblSlFromEnterMoney.Foreground = Brushes.Red;
                        error = true;
                    }

                    Slm.StopLimitIsMarketOrder = Convert.ToBoolean(ChbxSlMarkerOrder.IsChecked);
                    if (!Slm.StopLimitIsMarketOrder)
                        if (!String.IsNullOrEmpty(TxbxSlSpred.Text))
                        {
                            Slm.StopLimitSpred = Convert.ToDouble(TxbxSlSpred.Text);
                            TxblSlSpred.Foreground = Brushes.White;
                        }
                        else
                        {
                            TxblSlSpred.Foreground = Brushes.Red;
                            error = true;
                        }

                    Slm.StopLimitBreakeven = Convert.ToDouble(TxbxSlBreakeven.Text);
                    Slm.StopLimitBreakOtstup = Convert.ToDouble(TxbxSlBreakevenOtstup.Text);


                } 
                #endregion

                
                if (error)
                {
                    new DialogOkCancel("Ошибки в настройках", "Ошибки добавления");
                    return;
                }

                DialogResult = true;

                Close();
            }
            catch
            {
            }

        }

        private void BtnCancel_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }

        private void CmbxTypeStop_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (((ComboBox) sender).SelectedItem != null)
            {
                if (((ComboBox) sender).SelectedItem.ToString() == Cfg.StopLimit)
                {
                    ColorOfTextBlock(Brushes.White, Brushes.DarkGray, Brushes.DarkGray, true, false, false);
                }
                if (((ComboBox) sender).SelectedItem.ToString() == Cfg.TakeProfit)
                {
                    ColorOfTextBlock(Brushes.DarkGray, Brushes.White, Brushes.DarkGray, false, true, false);
                }
                if (((ComboBox) sender).SelectedItem.ToString() == Cfg.LinkedOrder)
                {
                    ColorOfTextBlock(Brushes.White, Brushes.DarkGray, Brushes.White, true, false, true);
                }
                if (((ComboBox) sender).SelectedItem.ToString() == Cfg.StopTakeOrder)
                {
                    ColorOfTextBlock(Brushes.White, Brushes.White, Brushes.DarkGray, true, true, false);
                }
                if (((ComboBox) sender).SelectedItem.ToString() == Cfg.TakeProfitLimitOrder)
                {
                    ColorOfTextBlock(Brushes.DarkGray, Brushes.DarkGray, Brushes.White, false, false, true);
                }
            }
            EnableTypeCalculation();
           
        }

        private void ColorOfTextBlock(Brush stop, Brush take, Brush limit, bool stopEnable, bool takeEnable, bool limitEnable)
        {
            GpbxStopLimit.IsEnabled = stopEnable;
            TxblSlOtstup.Foreground = stop;
            TxbxSlOtstupV.Foreground = stop;
            TxblSlFromEnterMoney.Foreground = stop;
            TxblSlSpred.Foreground = stop;
            TxbxSlSpredV.Foreground = stop;
            ChbxSlMarkerOrder.Foreground = stop;
            TxbxlSlBreakeven.Foreground = stop;
            TxbxSlBreakevenV.Foreground = stop;
            TxblSlBreakevenOtstup.Foreground = stop;

            GpbxTakeProfit.IsEnabled = takeEnable;
            TxblTpPriceActivation.Foreground = take;
            TxblTpFromEnterMoney.Foreground = take;
            TxblTpOtstupMinMax.Foreground = take;
            TxblTpSpred.Foreground = take;
            TxbxTpPriceActivationV.Foreground = take;
            TxbxTpOtstupMinMaxV.Foreground = take;
            TxbxTpSpredV.Foreground = take;
            ChbxTpMarkerOrder.Foreground = take;

            GpbxLimitOrder.IsEnabled = limitEnable;
            TxblLimitPrice.Foreground = limit;
            TxbxLimitPriceV.Foreground = limit;
            TxblLimitFromEnterMoney.Foreground = limit;

            if (GpbxStopLimit.IsEnabled || GpbxTakeProfit.IsEnabled)
            {
                textBlock20.Foreground = Brushes.White;
                CmbxKillOrderType.IsEnabled = true;
                textBlock19.Foreground = Brushes.White;
                TxbxTimeWiatOpenPoz.IsEnabled = true;
                textBlock22.Foreground = Brushes.White;
                TxbxSpredForKillOrderOpen.IsEnabled = true;
            }
            else
            {
                textBlock20.Foreground = Brushes.DarkGray;
                CmbxKillOrderType.IsEnabled = false;
                textBlock19.Foreground = Brushes.DarkGray;
                TxbxTimeWiatOpenPoz.IsEnabled = false;
                textBlock22.Foreground = Brushes.DarkGray;
                TxbxSpredForKillOrderOpen.IsEnabled = false;
            }

            
        }

        private void CmbxTypeCalculation_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            EnableTypeCalculation();
        }

        /// <summary>
        /// В зависимости от типа расчета делаем активные области
        /// </summary>
        private void EnableTypeCalculation()
        {
            if (CmbxTypeCalculation.SelectedItem != null)
            {
                if (CmbxTypeCalculation.SelectedItem.ToString() == Cfg.StopTypeCalculationFromDeposit)
                {
                    if (GpbxStopLimit.IsEnabled)
                    {
                        TxblSlOtstup.Foreground = Brushes.DarkGray;
                        TxbxSlOtstup.IsEnabled = false;
                        TxbxSlOtstupV.Foreground = Brushes.DarkGray;
                        CmbxSlOtstup.IsEnabled = false;
                        TxblSlFromEnterMoney.Foreground = Brushes.White;
                        TxbxSlFromEnterMoney.IsEnabled = true;
                    }
                    if (GpbxTakeProfit.IsEnabled)
                    {
                        TxblTpPriceActivation.Foreground = Brushes.DarkGray;
                        TxbxTpPriceActivation.IsEnabled = false;
                        TxbxTpPriceActivationV.Foreground = Brushes.DarkGray;
                        CmbxTpPriceActivation.IsEnabled = false;
                        TxblTpFromEnterMoney.Foreground = Brushes.White;
                        TxbxTpFromEnterMoney.IsEnabled = true;
                    }
                    if (GpbxLimitOrder.IsEnabled)
                    {
                        TxblLimitPrice.Foreground = Brushes.DarkGray;
                        TxbxLimitPrice.IsEnabled = false;
                        TxbxLimitPriceV.Foreground = Brushes.DarkGray;
                        CmbxLimitPrice.IsEnabled = false;
                        TxblLimitFromEnterMoney.Foreground = Brushes.White;
                        TxbxLimitFromEnterMoney.IsEnabled = true;
                    }
                }
                if (CmbxTypeCalculation.SelectedItem.ToString() == Cfg.StopTypeCalculationBySetting)
                {
                    if (GpbxStopLimit.IsEnabled)
                    {
                        TxblSlOtstup.Foreground = Brushes.White;
                        TxbxSlOtstup.IsEnabled = true;
                        TxbxSlOtstupV.Foreground = Brushes.White;
                        CmbxSlOtstup.IsEnabled = true;
                        TxblSlFromEnterMoney.Foreground = Brushes.DarkGray;
                        TxbxSlFromEnterMoney.IsEnabled = false;
                    }
                    if (GpbxTakeProfit.IsEnabled)
                    {
                        TxblTpPriceActivation.Foreground = Brushes.White;
                        TxbxTpPriceActivation.IsEnabled = true;
                        TxbxTpPriceActivationV.Foreground = Brushes.White;
                        CmbxTpPriceActivation.IsEnabled = true;
                        TxblTpFromEnterMoney.Foreground = Brushes.DarkGray;
                        TxbxTpFromEnterMoney.IsEnabled = false;
                    }
                    if (GpbxLimitOrder.IsEnabled)
                    {
                        TxblLimitPrice.Foreground = Brushes.White;
                        TxbxLimitPrice.IsEnabled = true;
                        TxbxLimitPriceV.Foreground = Brushes.White;
                        CmbxLimitPrice.IsEnabled = true;
                        TxblLimitFromEnterMoney.Foreground = Brushes.DarkGray;
                        TxbxLimitFromEnterMoney.IsEnabled = false;
                    }
                }
            }

        }

        private void CheckBoxEnable()
        {
            if (GpbxStopLimit.IsEnabled)
                if (ChbxSlMarkerOrder.IsChecked != null && !(bool) ChbxSlMarkerOrder.IsChecked)
                {
                    TxblSlSpred.Foreground = Brushes.White;
                    TxbxSlSpred.IsEnabled = true;
                    TxbxSlSpredV.Foreground = Brushes.White;
                    CmbxSlSpred.IsEnabled = true;
                }
                else
                {
                    TxblSlSpred.Foreground = Brushes.DarkGray;
                    TxbxSlSpred.IsEnabled = false;
                    TxbxSlSpredV.Foreground = Brushes.DarkGray;
                    CmbxSlSpred.IsEnabled = false;
                }

            if (GpbxTakeProfit.IsEnabled)
                if (ChbxTpMarkerOrder.IsChecked != null && !(bool)ChbxTpMarkerOrder.IsChecked)
                {
                    TxblTpSpred.Foreground = Brushes.White;
                    TxbxTpSpred.IsEnabled = true;
                    TxbxTpSpredV.Foreground = Brushes.White;
                    CmbxTpSpred.IsEnabled = true;
                }
                else
                {
                    TxblTpSpred.Foreground = Brushes.DarkGray;
                    TxbxTpSpred.IsEnabled = false;
                    TxbxTpSpredV.Foreground = Brushes.DarkGray;
                    CmbxTpSpred.IsEnabled = false;
                }
        }

        private void ChbxTpMarkerOrder_Click(object sender, RoutedEventArgs e)
        {
            CheckBoxEnable();
        }

        private void ChbxSlMarkerOrder_Click(object sender, RoutedEventArgs e)
        {
            CheckBoxEnable();
        }

        private void ChbxTpMarkerOrder_Checked(object sender, RoutedEventArgs e)
        {
            CheckBoxEnable();
        }

        private void ChbxSlMarkerOrder_Checked(object sender, RoutedEventArgs e)
        {
            CheckBoxEnable();
        }

        #region Обработка получение текстобксом фокуса и потери его, замена запятой на точку
        private void TxbxLostFocus(object sender, RoutedEventArgs e)
        {
            if (((TextBox)sender).Text == "")
                ((TextBox)sender).Text = 0.ToString();

            char pointChar = ',';
            string str = (1.2).ToString();
            if (str.IndexOf('.') > 0) pointChar = '.';

            if (pointChar == ',')
                ((TextBox)sender).Text = ((TextBox)sender).Text.Replace('.', pointChar);

            if (pointChar == '.')
                ((TextBox)sender).Text = ((TextBox)sender).Text.Replace(',', pointChar);
        }

        private void TxbxGotFocus(object sender, RoutedEventArgs e)
        {
            try
            {
                if (((TextBox)sender).Text != "")
                {
                    if (Convert.ToDouble(((TextBox)sender).Text) == 0)
                    {
                        ((TextBox)sender).Text = "";
                    }
                }
            }
            catch
            {
                ((TextBox)sender).Text = "";
            }
        }

        private void TxbxPreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            if (!Char.IsDigit(e.Text, 0))
                e.Handled = true;

            if ((e.Text.IndexOf('.') == 0 || e.Text.IndexOf(',') == 0) && ((TextBox)sender).Text.IndexOf('.') == -1 && ((TextBox)sender).Text.IndexOf(',') == -1)
                e.Handled = false;
        }

        private void TxbxDitgitPreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            if (!Char.IsDigit(e.Text, 0))
                e.Handled = true;
        }
        #endregion

    }
}
